﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using FFS.Model;
using FFS.BLL;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;

namespace FFS
{
    public partial class frmLogin : Form
    {
        public frmLogin()
        {
            InitializeComponent();
        }

        LoginUserInfo user = new LoginUserInfo();
        List<LoginUserInfo> userList = new List<LoginUserInfo>();
        LoginUserService userService = new LoginUserService();
        SystemLogService sysLogService = new SystemLogService();

        private void btn_LoginIn_Click(object sender, EventArgs e)
        {
            string LoginUserName = this.cmb_LoginUserName.Text.ToString().Trim();
            string LoginPassword = this.txt_LoginPassword.Text;

            bool success = this.VerifyLogin(LoginUserName, LoginPassword);

            if (success)
            {
                this.lbl_errorMsg.Text = "";
                this.lbl_errorMsg.Visible = false;
                if (!this.cmb_LoginUserName.AutoCompleteCustomSource.Contains(LoginUserName))
                {
                    this.cmb_LoginUserName.AutoCompleteCustomSource.Add(LoginUserName);
                }
                Context._Login_UserName = this.cmb_LoginUserName.Text.ToString().Trim();

                /*记住密码处理*/
                if (this.checkBox_RememberPassword.Checked)
                {
                    this.RememberPassword(LoginUserName, LoginPassword);
                }
                else
                {
                    this.RememberPassword(LoginUserName, "");
                }

                sysLogService.ManageSystemLog().CreateLoginUserActionLog(LoginUserName, "Login", "Login Success", Context._Login_UserName);

                frmMain main = new frmMain();
                this.Hide();
                main.Show();
            }
            else
            {
                sysLogService.ManageSystemLog().CreateLoginUserActionLog(LoginUserName, "Login", "Login Failed", "");
                this.lbl_errorMsg.Text = "用户名或者密码不正确";
                this.lbl_errorMsg.Visible = true;
                this.txt_LoginPassword.Text = "";
                //this.txt_LoginPassword.Focus();
            }
        }

        private bool VerifyLogin(string loginUserName, string loginPassword)
        {
            return userService.ManageLoginUser().VerifyLogin(loginUserName, loginPassword);
        }

        private void SaveLoginHistory()
        {
            //获取保存历史的文件
            string filePath = System.IO.Path.Combine(Application.StartupPath, "history.txt");
            System.IO.StreamWriter writer = new System.IO.StreamWriter(filePath, false, Encoding.Default);

            foreach (string loginUserName in this.cmb_LoginUserName.AutoCompleteCustomSource)
            {
                if (loginUserName != null)
                {
                    writer.WriteLine(loginUserName.ToString());
                }
            }

            writer.Flush();
            writer.Close();

        }

        private void LoadLoginHistory()
        {
            //通过序列化和反序列化存储和获取历史登陆成功的用户名和密码
            if (System.IO.File.Exists("sys.bin"))
            {
                IFormatter formatter = new BinaryFormatter();
                Stream stream = new FileStream("sys.bin", FileMode.Open, FileAccess.Read, FileShare.Read);
                userList = (List<LoginUserInfo>)formatter.Deserialize(stream);

                for (int i = 0; i < userList.Count; i++)
                {
                    if (i == 0 && userList[i].LoginPassword != "")
                    {
                        this.txt_LoginPassword.Text = userList[i].LoginPassword;
                        this.checkBox_RememberPassword.Checked = true;
                    }

                    this.cmb_LoginUserName.Items.Add(userList[i].LoginUserName);
                    this.cmb_LoginUserName.AutoCompleteCustomSource.Add(userList[i].LoginUserName);
                }

                this.cmb_LoginUserName.SelectedIndex = 0;
                stream.Close();
            }
        }

        private void frmLogin_Load(object sender, EventArgs e)
        {
            this.lbl_errorMsg.Text = "";
            this.lbl_errorMsg.Visible = false;
            this.cmb_LoginUserName.Text = "admin";
            this.txt_LoginPassword.Text = "admin";
            LoadLoginHistory();
        }

        private void frmLogin_FormClosed(object sender, FormClosedEventArgs e)
        {
            SaveLoginHistory();
        }

        private void linkLbl_FindPassword_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            System.Diagnostics.Process.Start("http://www.hao123.com");
        }

        private void RememberPassword(string userName, string userPassword)
        {
            user.LoginUserName = userName;
            user.LoginPassword = userPassword;

            for (int i = 0; i < userList.Count; i++)
            {
                if (userList[i].LoginUserName == userName)
                {
                    userList.RemoveAt(i);
                    break;
                }
            }
            userList.Insert(0,user);/*添加当前最新登陆信息到保存序列的第一个位置*/

            //将当前的登陆密码保存到登陆用户选择列表中，并登陆成功的用户名排列到第一位。
            for (int i = 0; i < this.cmb_LoginUserName.Items.Count; i++)
            {
                if (this.cmb_LoginUserName.Items[i].ToString() == userName)
                {
                    this.cmb_LoginUserName.Items.RemoveAt(i);
                    break;
                }
            }
            this.cmb_LoginUserName.Items.Add(userName);

            IFormatter formatter = new BinaryFormatter();
            Stream stream = new FileStream("sys.bin", FileMode.Create, FileAccess.Write, FileShare.ReadWrite);
            formatter.Serialize(stream, userList);

        }

        private void SelectUserPasswordByLoginUserName()
        {
            for (int i = 0; i < userList.Count; i++)
            {
                if (this.cmb_LoginUserName.Text == userList[i].LoginUserName)
                {
                    this.txt_LoginPassword.Text = userList[i].LoginPassword;
                    if (this.txt_LoginPassword.Text != "")
                    {
                        this.checkBox_RememberPassword.Checked = true;
                    }
                    break;
                }
            }
        }

        private void cmb_LoginUserName_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.SelectUserPasswordByLoginUserName();
        }

        private void cmb_LoginUserName_KeyUp(object sender, KeyEventArgs e)
        {
            this.SelectUserPasswordByLoginUserName();            
        }

        private void cmb_LoginUserName_KeyDown(object sender, KeyEventArgs e)
        {
            this.txt_LoginPassword.Text = "";
            this.checkBox_RememberPassword.Checked = false;
        }

    }
}